package cn.com.thshuda.rabbitmq.server;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashSet;
import java.util.Map;

/**
 * @author: wsd
 * @date: 2021/6/10 15:30
 */
@Component
public class DirectReceiver {
    HashSet hashSet = new HashSet();

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "labelQueues"),
                    exchange = @Exchange(value = "labelExchange")
            )
    )
    @RabbitHandler
    public void handle(@Payload Map msg, Channel channel, @Headers Map<String,Object> headers) throws IOException {
        // 获取到AMQP信道中的消息的唯一编号TagId，方便返回应答模式告知消息已接到
        Long tag = (Long)headers.get(AmqpHeaders.DELIVERY_TAG);
        try {
            // 应答模式确认接收到消息,后面那个参数如果是false，就是只确认签收当前消息，如果是true，则签收全部比当前TagId小的消息
            channel.basicAck(tag,false);
            System.out.println(msg);
            hashSet.add(msg);
            System.out.println("请求了"+hashSet.size());
            if(hashSet.size() >11){
              int  i = 1 / 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
            rabbitTemplate.convertSendAndReceive("labelExceptionExchange","",msg);
            channel.basicNack(tag,false,true);
        }
    }

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "labelExceptionQueues"),
                    exchange = @Exchange(value = "labelExceptionExchange")
            )
    )
    @RabbitHandler
    public void handled(@Payload Map msg, Channel channel, @Headers Map<String,Object> headers) throws IOException {
        // 获取到AMQP信道中的消息的唯一编号TagId，方便返回应答模式告知消息已接到
        System.out.println("异常消息"+msg);
        Long tag = (Long)headers.get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(tag,false);
    }
}
